<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-05-30 11:43:25
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2024-04-24 10:23:33
-->
<template>
	<div v-loading="loading">
		<el-input v-model="query" placeholder="请输入菜单名称" @input="onQueryChanged" />
		<!-- default-expand-all -->
		<el-tree
			class="mt10"
			v-bind="$attrs"
			ref="treeRef"
			node-key="id"
			:default-expanded-keys="defaultExpandedKeys"
			:expand-on-click-node="false"
			highlight-current
			draggable
			:current-node-key="currentNodeKey"
			:data="treeData"
			:props="defaultProps"
			:filter-node-method="filterMethod"
			:height="450"
			@node-drop="handleDrop"
			@node-drag-start="dragStart"
		>
			<template #default="{ node, data }">
				<span class="f-between w-100" @mouseenter="onMouseenter(node, data)" @mouseleave="onMouseleave(node, data)">
					<span
						:style="{
							color: data.id === currentId ? '#1f5aff' : '',
							'margin-right': '2rem',
						}"
					>
						{{ node.label }}
						<span v-if="data.type == 1" class="text-auth-tag">权限</span>
					</span>
					<span v-show="data.show">
						<el-button type="primary" text>
							<icon-drag theme="outline" fill="#333" />
							移动位置
						</el-button>
					</span>
				</span>
			</template>
		</el-tree>
	</div>
</template>

<script setup lang="ts">
import apiMod from '@/apiMod/index'
import { ElMessage } from 'element-plus'
import { useCrudStore } from '@/stores/crud'
const { setMenuTreeData } = useCrudStore()
const query = ref('')
const treeData = ref([])
const treeRef = ref()
const currentId = ref()
const props = defineProps({
	deviceType: [String, Number],
})
const defaultExpandedKeys = ref([-1])
const currentNodeKey = ref(-1)
const defaultProps = {
	value: 'id',
	label: 'label',
	children: 'children',
}
const loading = ref(false)
const onQueryChanged = (query: string) => {
	treeRef.value!.filter(query)
}

const filterMethod = (value: string, data: any) => {
	if (!value) return true
	const reg = new RegExp('[\\u4E00-\\u9FFF]+', 'g')
	if (reg.test(value)) {
		return data.label.includes(value)
	} else {
    const name = data.permission?data.permission:data.label
		return name.includes(value)
	}
}

const dragStart = (node) => {
	currentId.value = node.data.id
}
const onMouseenter = (node, data) => {
	data.show = true
}
const onMouseleave = (node, data) => {
	data.show = false
}

const updateDrag = (data) => {
	// 更新数据
	apiMod
		.sys_menu_edit({
			...data,
			menuId: data.id,
		})
		.then((res) => {
			ElMessage.success('调整成功')
			getInitData()
		})
}

const handleDrop = (draggingNode, dropNode, dropType) => {
	// 父级id相同移动排序，不同调整上下级
	const dragData = draggingNode?.data
	const dropData = dropNode?.data
	if (dragData.parentId === dropData.parentId) {
		let sort = 999
		if (dropType === 'before') {
			sort = dragData?.sort - 1
		} else {
			sort = dropData.sort + 1
		}
		dragData.sort = sort
		updateDrag(dragData)
	} else {
		updateDrag({
			...dragData,
			menuId: dragData.id,
			parentId: dropType == 'inner' ? dropData.id : dropData.parentId,
		})
	}
}

const updateNodeInfo = (data, newChild, type) => {
	if (type == 'add') {
		defaultExpandedKeys.value = [-1, data.id]
		currentNodeKey.value = data.id
	} else {
		defaultExpandedKeys.value = [-1, data.parentId]
		currentNodeKey.value = data.parentId
	}
	getInitData()
}

const removeNode = (node, data) => {
	const parent = data.parent
	const children = parent.data?.children || parent.children
	const index = children.findIndex((d) => d.id === node.id)
	children.splice(index, 1)
	treeData.value = [...treeData.value]
}

const getInitData = () => {
	loading.value = true
	apiMod
		.admin_menu({ deviceType: props.deviceType })
		.then((res) => {
			loading.value = false
			const data = [{ label: '根目录', id: -1, children: res.data }]
			// const keys = res.data.map((item) => item.id)
			// treeRef.value!.setExpandedKeys([...keys, -1])
			treeData.value = data
			setMenuTreeData(data)
		})
		.catch(() => {
			loading.value = false
		})
}
onMounted(() => {
	getInitData()
})

defineExpose({
	removeNode,
	updateNodeInfo,
})
</script>

<style scoped>
.text-auth-tag {
	font-size: 10px;
	color: #fff;
	background: var(--el-color-primary);
	padding: 2px 4px;
	border-radius: 20px;
}
</style>
